class VastApi
  class Categories < Hash
    attr_reader :response,:xml, :url, :vast

    delegate :attributes, :listings, :categories, :to=>:vast

    def initialize(vast)
      @vast = vast
      @url = "#{@vast.api_url}categories?#{@vast.api_query}"
      @response = Typhoeus::Request.get(@url)
      @xml = Nokogiri::XML(@response.body)
      populate
    end

    def attr(var_name)
      if var = @xml.at(var_name)
        var.text
      elsif var = @xml.at('//v:'+var_name)
        var.text
      elsif var = @xml.at('//o:'+var_name)
        var.text
      else
        nil
      end
    end

    private

    def populate
      @xml.xpath('//xmlns:entry/v:category').each do |node|
        node.extend(Category)
        self[node['id']] = {
          :name => node['name'],
          :count => node['count']
        }
        if node.element_children.length > 0
          self[node['id']][:children] = node.categories
        end
      end
    end
  end
end
